<?php

namespace app\models;

use Slim;
use slimExt\base\Model;
use slimExt\DataCollector;
use slimExt\base\IdentityInterface;

/**
 * Class Users
 * @package app\models
 *
 * @property string $username
 * @property string $password
 * @property string $email
 * @property string $avatar
 * @property int $id
 * @property int $lastLogin
 * @property int $updateTime
 * @property int $createTime
 */
class Users extends Model implements IdentityInterface
{
    const ROLE_SUPPER_MAN   = 1;
    const ROLE_MANAGER      = 2;
    const ROLE_EDITOR       = 3;
    const ROLE_NORMAL       = 4;

    const DEFAULT_AVATAR = '/assets/images/logo_mini.png';

    /**
     * define some default value
     * @var array
     */
    protected $data = [
        'role' => self::ROLE_NORMAL
    ];

    public function columns()
    {
        return [
            'id'          => 'int',
            'gid'         => 'int', // 用户组id
            'username'    => 'string',
            'password'    => 'string',
            'avatar'      => 'string',
            'email'       => 'string',
            'createTime'  => 'int',
            'updateTime'  => 'int',
        ];
    }

    public function rules()
    {
        return [

        ];
    }

    public static function dataPath()
    {
        return Slim::alias(slim_config('tables.user'));
    }

    public static function getUsers()
    {
        return DataCollector::parseJson(self::dataPath());
    }

    /**
     * @param $name
     * @return mixed
     */
    public static function findByName($name)
    {
        foreach (self::getUsers() as $user) {
            if ($user['username'] === trim($name)) {
                return new static($user);
            }
        }

        return null;
    }

    public static function findIdentity($id)
    {
        foreach (self::getUsers() as $user) {
            if ($user['id'] === (int)$id ) {
                return new static($user);
            }
        }

        return null;
    }

    /**
     * @param $name
     * @return mixed
     */
    public static function findByEmail($name)
    {
        foreach (self::getUsers() as $user) {
            if ($user['email'] === trim($name)) {
                return new static($user);
            }
        }

        return null;
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return null;
    }

    public function getId()
    {
        return $this->get('id', 0);
    }

    /**
     * @return string a key that is used to check the validity of a given identity ID.
     * @see validateAuthKey()
     */
    public function getAuthKey()
    {
        return null;
    }

    /**
     * Validates the given auth key.
     * @param string $authKey the given auth key
     * @return boolean whether the given auth key is valid.
     * @see getAuthKey()
     */
    public function validateAuthKey($authKey)
    {
        return $authKey === $this->getAuthKey();
    }

    /**
     * @param $username
     * @param $password
     * @return bool|string
     */
    public static function login($username, $password)
    {
        $lang = Slim::$app->language;

        if ( !$username || !$password ) {
            return $lang->tran('missOrErrorParam');
        }

        if ( !$user= self::findByName($username) ) {
            return '用户不存在！';
        }

        if ( !password_verify($password, $user['password']) ) {
            return '密码错误！';
        }

        Slim::get('user')->login($user);

        return true;
    }

    /**
     * @return array|bool|int
     */
    public function register()
    {
        // check username
        if ( self::findByName($this->username) ) {
            return "username [{$this->username}] have already registered.";
        }

        // check email
        if ( self::findByEmail($this->email) ) {
            return "email [{$this->email}] have already used.";
        }

        // check password
        if ( $this->password !== $this->repassword ) {
            return "The two passwords you typed don't match.";
        }

        $users = static::getUsers();

        $this->password   = password_hash($this->password, PASSWORD_BCRYPT);
        $this->avatar     = self::DEFAULT_AVATAR;
        $this->createTime = time();
        $this->id = count($users)+1;

        $newUser = $this->all();
        unset($newUser['repassword'],$newUser['csrf_name'],$newUser['csrf_value']);
        $users[] = $newUser;

        $path = self::dataPath();

        if ( file_put_contents($path, json_encode($users)) ) {
            return true;
        }

        return 'register failure!!';
    }
}